﻿#if NET40
using System;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace DaveSexton.Labs
{
  internal static class DispatcherExtensions
  {
    public static Task InvokeAsync(this Dispatcher dispatcher, Action callback)
    {
      Contract.Requires(dispatcher != null);
      Contract.Requires(callback != null);
      Contract.Ensures(Contract.Result<Task>() != null);

      var operation = dispatcher.BeginInvoke(callback);

      var source = new TaskCompletionSource<bool>();

      operation.Completed += (_, __) => source.SetResult(true);
      operation.Aborted += (_, __) => source.SetCanceled();

      return source.Task;
    }
  }
}
#endif